<template>
  <doc-alert title="用户体系" url="https://doc.iocoder.cn/user-center/" />
  <doc-alert title="三方登陆" url="https://doc.iocoder.cn/social-user/" />
  <doc-alert title="Excel 导入导出" url="https://doc.iocoder.cn/excel-import-and-export/" />

  <el-row :gutter="20">
    <!-- 左侧机构树 -->
    <!-- <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col> -->
    <el-col :span="24" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
          <el-form-item label="员工编号" prop="username">
            <ns-input
              v-model="queryParams.username"
              placeholder="请输入员工编号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="员工姓名" prop="nickname">
            <ns-input
              v-model="queryParams.nickname"
              placeholder="请输入员工姓名"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <ns-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="归属机构" prop="deptId">
            <el-cascader
              v-model="queryParams.deptId"
              clearable
              placeholder="请选择归属机构"
              :options="deptList"
              :props="cascaderProps"
              filterable
              :filter-method="sysFilterMethod"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="归属系统" prop="sysId">
            <el-cascader
              v-model="queryParams.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              :filter-method="sysFilterMethod"
              clearable
              class="!w-240px"
          /></el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              class="!w-240px"
            >
              <el-option label="关闭" :value="1" />
              <el-option label="启用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="数据标准权限" prop="dataStandardId">
            <el-select
              v-model="queryParams.dataStandardId"
              placeholder="请选择数据标准权限"
              clearable
              class="!w-240px"
            >
              <el-option 
                v-for="item in dataStandardList" 
                :key="item.id" 
                :label="item.dataStandardName" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="归属系统权限" prop="systemPriId">
            <el-cascader
              v-model="queryParams.systemPriId"
              clearable
              placeholder="请选择归属系统"
              :options="systemPriList"
              :props="systemCascaderProps"
              filterable
              :filter-method="sysFilterMethod"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="归属机构权限" prop="deptPreId">
            <el-cascader
              v-model="queryParams.deptPreId"
              placeholder="请选择归属机构权限"
              :props="cascaderProps"
              :options="deptPreList"
              filterable
              :filter-method="sysFilterMethod"
              clearable
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="角色权限" prop="roleId">
            <el-select
              v-model="queryParams.roleId"
              placeholder="请选择角色权限"
              clearable
              class="!w-240px"
            >
              <el-option 
                v-for="item in roleList" 
                :key="item.id" 
                :label="item.name" 
                :value="item.id" 
              />
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="24" class="mb-12px text-right">
              <el-button @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-form-item>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['system:user:create']"
            >新增
          </el-button>
          <el-button type="warning" plain @click="handleImport" v-hasPermi="['system:user:import']">
            导入
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['system:user:export']"
            >导出
          </el-button>
          <el-button type="success" plain @click="handleCopy" v-hasPermi="['system:user:create']"
            >权限复制
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleDeleteList"
            :disabled="ids.length <= 0"
            v-hasPermi="['system:user:delete']"
            >删除
          </el-button>
        </el-form-item>
        <el-table v-loading="loading" :data="list" @selection-change="selectionChange">
          <el-table-column type="selection" align="center" />
          <!-- <el-table-column label="用户编号" align="center" key="id" prop="id" /> -->
          <el-table-column
            label="员工编号"
            align="center"
            prop="username"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="员工姓名"
            align="center"
            prop="nickname"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="归属机构"
            align="center"
            prop="deptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="归属系统"
            align="center"
            prop="sysName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号码"
            align="center"
            prop="mobile"
            width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="邮箱"
            align="center"
            prop="email"
            width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="性别"
            align="center"
            prop="mobile"
            width="120"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              {{ sexList[scope.row.sex] }}
            </template>
          </el-table-column>
          <el-table-column
            label="用户类型"
            align="center"
            prop="type"
            width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="状态" key="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            :show-overflow-tooltip="true"
            width="180"
          />
          <el-table-column label="操作" align="center" width="360">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button
                  type="primary"
                  link
                  @click="operDetail(scope.row.id)"
                  v-hasPermi="['system:user:detail']"
                  >查看
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['system:user:update']"
                  >修改
                </el-button>
                <el-button
                  type="danger"
                  link
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['system:user:delete']"
                  >删除
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:update-password']"
                  >重置密码
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleRole(scope.row)"
                  v-hasPermi="['system:permission:assign-user-role']"
                  >分配角色
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="handleAuthorization(scope.row)"
                  v-hasPermi="['system:permission:assign-user-role']"
                  >数据授权
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
      <el-dialog v-model="resetPwdDia" title="重置密码" width="400px">
        <el-form-item label="重置密码">
          <ns-input v-model="resetPasswordValue" />
          <div
            class="tip"
            v-if="
              passwordRule.includeDigits ||
              passwordRule.includeLetters ||
              passwordRule.includeSpecialChars
            "
          >
            必须含
            <span v-if="passwordRule.includeDigits">数字，</span>
            <span v-if="passwordRule.includeLetters">字母，</span>
            <span v-if="passwordRule.includeSpecialChars">特殊字符（!@#$%^&*），</span>
            <span v-if="passwordRule.length"
              ><span
                v-if="
                  passwordRule.includeDigits ||
                  passwordRule.includeLetters ||
                  passwordRule.includeSpecialChars
                "
                >以及</span
              >最小长度为{{ passwordRule.length }}</span
            >
          </div>
        </el-form-item>
        <template #footer>
          <div>
            <el-button type="primary" @click="confirmResetPwd">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog
        v-model="uploadResultDia"
        title="导入结果"
        width="70%"
        v-if="uploadResultDia"
        align-center
      >
        <h2 class="mb-25px">创建成功数量：{{ successQuantity }}</h2>
        <h2 class="my-25px">更新成功数量：{{ uploadQuantity }}</h2>
        <h2 class="my-25px">上传失败数量：{{ failTable.data.length }}</h2>
        <AsyncTable
          v-bind="failTable"
          ref="failTableRef"
          max-height="340px"
          :showSift="false"
          :isPage="false"
        />
        <template #footer>
          <el-button type="primary" @click="uploadResultDia = false">确认</el-button>
        </template>
      </el-dialog>
    </el-col>
  </el-row>
  <!-- 添加或修改用户对话框 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 用户导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 权限复制对话框 -->
  <UserCopyForm ref="copyFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />
  <UserDetail
    :dialogVisible="dialogVisible"
    :id="currentId"
    v-if="dialogVisible"
    @close="dialogVisible = false"
  />
</template>
<script lang="tsx" setup>
import { sysFilterMethod } from '@/utils/selectFilter'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import UserForm from './UserForm.vue'
import UserImportForm from './UserImportForm.vue'
import UserCopyForm from './UserCopyForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import UserDetail from './UserDetail.vue'
import * as ConfigApi from '@/api/system/config'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { handleTree } from '@/utils/tree'
import {getSimpleRoleListAll} from '@/api/system/role'
defineOptions({ name: 'SystemUser' })
const sexList = ['未知', '男', '女']
const router = useRouter()
const dialogVisible = ref(false)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const uploadResultDia = ref(false)
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  username: undefined,
  nickname: undefined,
  mobile: undefined,
  status: undefined,
  deptId: undefined,
  createTime: [],
  dataStandardId: undefined,
  systemPriId: undefined,
  deptPreId: undefined,
  roleId: undefined
})
const queryFormRef = ref() // 搜索的表单
const uploadQuantity = ref(0)

const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const successQuantity = ref(0)

const failTable = ref({
  columns: [
    { type: 'index', label: '序号', width: '60px' },
    {
      label: '失败原因',
      render: ({ row }) => {
        return <div>{row}</div>
      },
      'min-width': '340px',
      'show-overflow-tooltip': true
    }
  ],
  data: []
})

const operDetail = (id) => {
  currentId.value = id
  dialogVisible.value = true
}

/** 查询列表 */
const getList = async (data, isDialog) => {
  if (isDialog) {
    successQuantity.value = data?.createUsernames?.length
    failTable.value.data = data?.failureUsernames
    uploadQuantity.value = data?.updateUsernames?.length
    uploadResultDia.value = true
  }
  loading.value = true
  try {
    const { count, data } = await UserApi.getUserPage(queryParams)
    list.value = data
    total.value = count
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理机构被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}

const ids = ref([])
const selectionChange = (e) => {
  ids.value = e.map((item) => item.id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 复制 */
const copyFormRef = ref()
const handleCopy = () => {
  copyFormRef.value.open(ids.value)
}

const handleDeleteList = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUserList(ids.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 修改用户状态 */
const handleStatusChange = async (row: UserApi.UserVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const params = ids.value.length > 0 ? { ...queryParams, ids: ids.value } : queryParams
    const data = await UserApi.exportUser(params)
    download.excel(data, '用户数据.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    case 'handleAuthorization':
      handleAuthorization(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const resetPwdDia = ref(false)
const currentId = ref()
const handleResetPwd = async (row: UserApi.UserVO) => {
  resetPwdDia.value = true
  currentId.value = row.id
  resetPasswordValue.value = ''
}

const resetPasswordValue = ref()
const confirmResetPwd = async () => {
  const password = resetPasswordValue.value
  if (password === '') {
    await message.confirm('重置密码未设置，将使用默认密码进行重置')
    await UserApi.resetUserPwd(currentId.value, defaultPassword.value)
    message.success('修改成功，新密码是：' + defaultPassword.value)
    resetPwdDia.value = false
    return
  }
  if (validatePassword(password, passwordRule.value)) {
    await UserApi.resetUserPwd(currentId.value, password)
    message.success('修改成功，新密码是：' + password)
    resetPwdDia.value = false
  } else {
    message.warning('密码校验失败')
  }
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}

// 数据授权
const handleAuthorization = (row) => {
  router.push({
    path: 'DataAuthorization',
    query: {
      id: row.id
    }
  })
}

const passwordRule = ref({
  includeDigits: true,
  includeLetters: true,
  includeSpecialChars: true,
  length: 10
})
const defaultPassword = ref()
const getConfig = async () => {
  const data = await ConfigApi.clientGet()
  defaultPassword.value = data.defaultPassword
  const complexities = data.passwordComplexity.split(',').map(Number)
  passwordRule.value = {
    includeDigits: complexities.indexOf(1) !== -1,
    includeLetters: complexities.indexOf(2) !== -1,
    includeSpecialChars: complexities.indexOf(3) !== -1,
    length: data.minLength
  }
}

const validatePassword = (password, passwordRule) => {
  // 构建正则表达式，根据校验规则生成对应的正则模式
  let pattern = '^'
  if (passwordRule.includeDigits) pattern += '(?=.*[0-9])' // 包含数字
  if (passwordRule.includeLetters) pattern += '(?=.*[a-zA-Z])' // 包含字母
  if (passwordRule.includeSpecialChars) pattern += '(?=.*[@#$%^&+=])' // 包含特殊字符，你也可以根据具体需要调整特殊字符的范围
  pattern += `.{${passwordRule.length},}$` // 最小长度

  // 创建正则表达式对象
  const regex = new RegExp(pattern)

  // 进行校验
  return regex.test(password)
}

const systemList = ref([])
const systemPriList = ref([])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
  systemPriList.value = handleTree(data, 'id', 'pid')
}
const deptList = ref([])
const deptPreList = ref([])
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  deptList.value = data
  deptPreList.value = data
}

//TODO 这个是构造的数据源。。。。。。。
const dataStandardList = ref([])
const getStandardList = async () => {
   const { data, count } = await dataStandardsPage({
    page:1,
    pageSize: 100,
    "status": CommonStatusEnum.ENABLE
  })
  // 只提取id和dataStandardName字段
  if(data && data.length > 0){
    dataStandardList.value = data.map(item => ({
      id: item.id,
      dataStandardName: item.dataStandardName
    }))
  }
}

//角色信息
const roleList = ref([])
const getSimpleRoleListAllMethod = async () => {
  const data = await getSimpleRoleListAll()
  console.log("xxx",data)
  roleList.value = data
}


/** 初始化 */
onMounted(() => {
  getList()
  getSimpleRoleListAllMethod()
  getStandardList()
  getConfig()
  getSystemList()
  getDeptList()
})
</script>
